/**
 * 邮件配置列表页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Switch,
  Tag,
  Popconfirm,
  message,
  Modal,
  Form,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  MailOutlined,
  SearchOutlined,
  ReloadOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import {
  getEmailConfigs,
  deleteEmailConfig,
  toggleEmailConfigStatus,
  sendTestEmail,
  type EmailConfigItem,
  type EmailSendTest,
  EncryptionType,
} from '@/services/emailConfig';

const { Search } = Input;

const EmailConfigList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<EmailConfigItem[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [activeOnly, setActiveOnly] = useState(false);
  const [testModalVisible, setTestModalVisible] = useState(false);
  const [testLoading, setTestLoading] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<EmailConfigItem | null>(null);
  const [testForm] = Form.useForm();

  // 获取邮件配置列表
  const fetchEmailConfigs = async () => {
    setLoading(true);
    try {
      const response = await getEmailConfigs({
        page: current,
        size: pageSize,
        search: searchText || undefined,
        active_only: activeOnly,
      });
      setData(response.items);
      setTotal(response.total);
    } catch (error: any) {
      message.error(error.message || '获取邮件配置列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmailConfigs();
  }, [current, pageSize, searchText, activeOnly]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrent(1);
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await deleteEmailConfig(id);
      message.success('删除成功');
      fetchEmailConfigs();
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  // 处理状态切换
  const handleToggleStatus = async (id: number) => {
    try {
      await toggleEmailConfigStatus(id);
      message.success('状态更新成功');
      fetchEmailConfigs();
    } catch (error: any) {
      message.error(error.message || '状态更新失败');
    }
  };

  // 处理发送测试邮件
  const handleSendTestEmail = async (values: any) => {
    if (!selectedConfig) return;
    
    setTestLoading(true);
    try {
      const testData: EmailSendTest = {
        config_id: selectedConfig.id,
        to_email: values.to_email,
        subject: values.subject || '邮件配置测试',
        content: values.content || '这是一封测试邮件，用于验证邮件配置是否正常工作。',
      };
      
      const result = await sendTestEmail(testData);
      if (result.success) {
        message.success(result.message);
        setTestModalVisible(false);
        testForm.resetFields();
      } else {
        message.error(result.message);
      }
    } catch (error: any) {
      message.error(error.message || '发送测试邮件失败');
    } finally {
      setTestLoading(false);
    }
  };

  // 打开测试邮件弹窗
  const openTestModal = (config: EmailConfigItem) => {
    setSelectedConfig(config);
    setTestModalVisible(true);
    testForm.setFieldsValue({
      subject: '邮件配置测试',
      content: '这是一封测试邮件，用于验证邮件配置是否正常工作。',
    });
  };

  // 获取加密类型标签
  const getEncryptionTag = (encryption: EncryptionType) => {
    const tagMap = {
      [EncryptionType.NONE]: { color: 'default', text: '无加密' },
      [EncryptionType.SSL]: { color: 'green', text: 'SSL' },
      [EncryptionType.STARTTLS]: { color: 'blue', text: 'STARTTLS' },
    };
    const config = tagMap[encryption] || tagMap[EncryptionType.NONE];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列定义
  const columns: ColumnsType<EmailConfigItem> = [
    {
      title: '配置名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: EmailConfigItem) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          {record.description && (
            <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
              {record.description}
            </div>
          )}
        </div>
      ),
    },
    {
      title: 'SMTP服务器',
      dataIndex: 'smtp_host',
      key: 'smtp_host',
      render: (text: string, record: EmailConfigItem) => (
        <div>
          <div>{text}:{record.smtp_port}</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            {record.username}
          </div>
        </div>
      ),
    },
    {
      title: '发件人',
      dataIndex: 'from_email',
      key: 'from_email',
      render: (text: string, record: EmailConfigItem) => (
        <div>
          <div>{text}</div>
          {record.from_name && (
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.from_name}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '加密方式',
      dataIndex: 'encryption',
      key: 'encryption',
      render: (encryption: EncryptionType) => getEncryptionTag(encryption),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (isActive: boolean, record: EmailConfigItem) => (
        <Switch
          checked={isActive}
          onChange={() => handleToggleStatus(record.id)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: EmailConfigItem) => (
        <Space size="small">
          <Tooltip title="发送测试邮件">
            <Button
              type="text"
              icon={<MailOutlined />}
              onClick={() => openTestModal(record)}
              disabled={!record.is_active}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => history.push(`/email-configs/edit/${record.id}`)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个邮件配置吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '邮件配置管理',
        breadcrumb: {},
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Search
              placeholder="搜索配置名称"
              allowClear
              style={{ width: 300 }}
              onSearch={handleSearch}
            />
            <Switch
              checked={activeOnly}
              onChange={setActiveOnly}
              checkedChildren="仅显示启用"
              unCheckedChildren="显示全部"
            />
            <Button icon={<ReloadOutlined />} onClick={fetchEmailConfigs}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => history.push('/email-configs/create')}
            >
              新建配置
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size || 10);
            },
          }}
        />
      </Card>

      {/* 测试邮件弹窗 */}
      <Modal
        title={`发送测试邮件 - ${selectedConfig?.name}`}
        open={testModalVisible}
        onCancel={() => {
          setTestModalVisible(false);
          testForm.resetFields();
        }}
        footer={null}
      >
        <Form
          form={testForm}
          layout="vertical"
          onFinish={handleSendTestEmail}
        >
          <Form.Item
            name="to_email"
            label="收件人邮箱"
            rules={[
              { required: true, message: '请输入收件人邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入收件人邮箱地址" />
          </Form.Item>

          <Form.Item
            name="subject"
            label="邮件主题"
            rules={[{ required: true, message: '请输入邮件主题' }]}
          >
            <Input placeholder="请输入邮件主题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="邮件内容"
            rules={[{ required: true, message: '请输入邮件内容' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入邮件内容" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={testLoading}>
                发送测试邮件
              </Button>
              <Button onClick={() => setTestModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default EmailConfigList;
